package service

import (
	"azfirewall-gateway/data"
	"azfirewall-gateway/utils"
	"crypto/tls"
	"errors"
	"github.com/syndtr/goleveldb/leveldb"
)

func GetCertByDomain(domainName string) (*tls.Certificate, error) {
	cert, err := data.DBP.CertDB.Get([]byte("Cert-"+domainName), nil)
	if err == leveldb.ErrNotFound {
		utils.MainLog.Debug("未找到站点[ " + domainName + " ]所对应的证书信息")
	} else if err != nil {
		utils.MainLog.Error("查询站点证书信息时发生错误：", err)
	}
	ckey, err := data.DBP.CertDB.Get([]byte("Key-"+domainName), nil)
	if err == leveldb.ErrNotFound {
		utils.MainLog.Debug("未找到站点[ " + domainName + " ]所对应的TSL秘钥信息")
	} else if err != nil {
		utils.MainLog.Error("查询站点TSL秘钥信息时发生错误：", err)
	}
	if cert != nil && ckey != nil {
		certObj, err := tls.X509KeyPair(cert, ckey)
		if err != nil {
			utils.MainLog.Error("加载证书过程中发生错误：", err)
		}
		return &certObj, nil
	} else {
		return nil, errors.New("未知的主机或无效的证书: " + domainName)
	}
}
